﻿using System;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using VitCode.BaseDataPageCreator.Setting;

namespace VitCode.Web.UserControls
{
    public partial class EnumFromXmlCtl : UserControl
    {
        /// <summary>
        /// 獲取或設置下拉清單的寬度(默認152px)
        /// </summary>
        public Unit Width
        {
            get { return DDList.Width; }
            set { DDList.Width = value; }
        }

        /// <summary>
        /// 獲取或設置所選項的索引
        /// </summary>
        public int SelectedIndex
        {
            get { return DDList.SelectedIndex; }
            set { DDList.SelectedIndex = value; }
        }

        /// <summary>
        /// 獲取或設置所選項的值
        /// </summary>
        public string SelectedValue
        {
            get { return DDList.SelectedValue; }
            set { DDList.SelectedValue = value; }
        }

        /// <summary>
        /// 獲取列表控制項中索引最小的選定項
        /// </summary>
        public ListItem SelectedItem
        {
            get { return DDList.SelectedItem; }
        }


        /// <summary>
        /// 
        /// </summary>
        public bool Enabled
        {
            get { return DDList.Enabled; }
            set { DDList.Enabled = value; }
        }

        public string Text
        {
            get
            {
                return DDList.SelectedValue;
            }
            set
            {
                SetData(value);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public string EnumNodeName { get; set; }


        /// <summary>
        /// 獲取選項的集合
        /// </summary>
        public ListItemCollection Items
        {
            get { return DDList.Items; }
        }


        private void Page_Load(object sender, EventArgs e)
        {
            // 在此處放置用戶代碼以初始化頁面
            if (!IsPostBack)
            {
                if (DDList.Width.IsEmpty)
                    DDList.Width = new Unit("156");
                SetData(DDList.SelectedValue);
            }
        }

        private void SetData(string val)
        {
            var enumHlp = new XmlEnumHelper();
            DDList.Items.Clear();
            NameValueCollection nvc = enumHlp.GetValue(EnumNodeName);

            for (int i = 0; i < nvc.Count; i++)
            {
                DDList.Items.Add(new ListItem(nvc.Get(i),nvc.GetKey(i)));
            }

            if (val != null && val.Length > 0)
                DDList.SelectedValue = val.Trim();
        }
    }
}
